<script setup lang="ts">
defineOptions({
  name: "safeDays"
});
import { ref, reactive } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { updateSafeDays } from "@/api/modules/operation";

interface RuleForm {
  num: number;
}

const operationDays = defineModel({ type: Number, default: 0 });

const visible = defineModel("visible", { type: Boolean, default: false });

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  num: operationDays.value
});

const rules = reactive<FormRules<RuleForm>>({
  num: [{ required: true, message: "请输入天数", trigger: ["blur", "change"] }]
});

const submitForm = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      const { num } = ruleForm;
      const id = 1;
      const params = { id, num };
      await updateSafeDays(params);
      operationDays.value = num;
      visible.value = false;
    } else {
      console.warn("error submit!  ", fields);
    }
  });
};
</script>

<template>
  <px-dialog v-model="visible" title="" width="300px" class="safe-days">
    <px-form ref="ruleFormRef" :model="ruleForm" :rules="rules" :label-width="0" status-icon>
      <px-form-item label="" prop="num">
        <px-input-number v-model="ruleForm.num" :min="0" :max="99999" placeholder="请输入天数" />
      </px-form-item>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="visible = false">取消</px-button>
        <px-button type="primary" @click="submitForm">确定</px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss">
.safe-days {
  .px-dialog__footer {
    padding-top: 0;
  }

  .px-input-number {
    width: 100%;
  }
}
</style>
